﻿// -----------------------------------------------------------------------
// <copyright file="CustomHandleErrorAttribute.cs" company="EPAM Systems">
////Copyright (c) EPAM Systems, 2012. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------

namespace MBOP.Website.CustomAttributes
{
	#region Usings

	using System;
	using System.Net;
	using System.Web.Mvc;
	using System.Web.Routing;

	using MBOP.Helpers.ExceptionHandling.ExceptionHandlers;
	using MBOP.Helpers.ExceptionHandling.Exceptions;

	#endregion

	/// <summary>
	/// Represents the application error end point handle.
	/// </summary>
	public sealed class CustomHandleErrorAttribute : HandleErrorAttribute
	{
		/// <summary>
		/// Calls when exception occurs.
		/// </summary>
		/// <param name="filterContext">Represents the filter context.</param>
		public override void OnException(ExceptionContext filterContext)
		{
			Exception exception = filterContext.Exception;

			string errorMessage = string.Empty;

			if (!(exception is BaseException))
			{
				ApplicationCommonExceptionHandler.HandleException(exception);
			}
			else
			{
				errorMessage = exception.Message;
			}

			filterContext.ExceptionHandled = true;

			if (!filterContext.HttpContext.Request.IsAjaxRequest())
			{
				RouteValueDictionary routeValues = new RouteValueDictionary();

				routeValues.Add("controller", "Error");
				routeValues.Add("action", "Index");
				routeValues.Add("message", errorMessage);

				filterContext.Result = new RedirectToRouteResult(routeValues);
			}
			else
			{
				filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
			}
		}
	}
}